<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../../static/assets/global/css/components.css">
    <link rel="stylesheet" type="text/css" href="../../static/assets/admin/pages/css/login.css">
    <script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
    <title>Title</title>
</head>
<body>
    <div class="content">
        <h3 class="form-title">商品列表</h3>
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>商品名</th>
                        <th>商品描述</th>
                        <th>商品价格</th>
                        <th>商品销量</th>
                        <th>商品库存</th>
                        <th>商品图片</th>
                    </tr>
                </thead>
                <tbody id="container">

                </tbody>
            </table>
        </div>
    </div>
</body>
<script>
    //定义全局商品信息数组
    var g_itemList = [];
    jQuery(document).ready(function(){
            $.ajax({
                type:"GET",
                url:"http://localhost:8080/item/list",
                xhrFields:{withCredentials: true},
                success:function(data){
                    if(data.status == "success"){
                        g_itemList = data.data;
                        reloadDom();
                    }else{
                        alert("获取商品列表失败，原因为"+data.data.errMsg);
                    }
                },
                error:function (data) {
                    alert("获取商品列表失败，原因是"+data.responseText);
                }
            });
    });
    
    function reloadDom() {
        for(var i=0; i<g_itemList.length; i++){
            var itemVo = g_itemList[i];
            var dom = "<tr data-id='"+itemVo.id+"' id='itemDetail"+itemVo.id+"'><td>"+
                        itemVo.title+"</td><td>"+itemVo.description+"</td><td>"+
                        itemVo.price+"</td><td>"+itemVo.sales+"</td><td>"+itemVo.stock+
                        "</td><td><img style='width: 100px; height: auto;' src='"+itemVo.imgUrl+"'></td></tr>";
            $("#container").append($(dom));

            /*
            * id=itemVo.id在闭包内会发生变化，不能访问
            * 将dom附上一个data-id，点击itemDetail元素的时候跳转
            * 并且获取点击元素data-id的值，作页面跳转
            */
            $("#itemDetail"+itemVo.id).on("click",function (e){
               window.location.href="getItem.html?id="+$(this).data("id");
            });
        }
    }
</script>
</html>